#include "display.h"

extern Globs g;
extern Stats s;

int Display::load() {
  char fname[NAME_LEN];
  m_buff = (char*)malloc(MAX_DISPLAY_SIZE);
  assert(m_buff);
  m_len = 0;

  sprintf(fname, "%s/%s.0", g.display_out_data_path, DISPLAY_NAME);
  ofp = fopen(fname, "w");
  if(ofp == NULL) {
    FATAL("fopen [%s] error", fname);
    return E_RET;
  }

  return S_RET;
}

void Display::reset() {
  m_len = 0;
}

void Display::append_display(char* text, bool is_seg) {
  const char* pterm;
  char* tc = NULL;
  const char* p;
  int termLen = 0;

  if(is_seg) {
    pterm = ICTCLAS_ParagraphProcess(text, 0); // segment
    if(pterm == NULL) {
      WARNING("segment error:text[%s]",
	  text);
      assert(0);
    }
    p = pterm;

    while(true) {
      tc = strchr(p, ' ');
      if(tc == NULL)
	break;
      termLen = tc-p;
      if(*p == ' '|| termLen == 0)
      {
	p = tc + 1;
	continue;
      }
      memcpy(m_buff+m_len, p, termLen);
      m_len += termLen;
      m_buff[m_len] = '\001';
      m_len += 1;
      assert(m_len < MAX_DISPLAY_SIZE);
      p = tc + 1;
    }
    m_buff[m_len] = '\t';
    m_len += 1;
  }
  else {
    termLen = strlen(text);
    strncpy(m_buff+m_len, text, termLen);
    m_len += termLen;
    m_buff[m_len] = '\t';
    m_len += 1;
    assert(m_len < MAX_DISPLAY_SIZE);
  }
}

void Display::serialize(uint32_t id) {
  DisplayFix fix;
  int ret;

  fix.size = m_len;
  fix.id   = id;

  ret = fwrite(&fix, sizeof(DisplayFix), 1, ofp);
  assert(ret == 1);

  ret = fwrite(m_buff, m_len, 1, ofp);
  assert(ret == 1);
}

void Display::chg_file(int fid) {
  char fname[NAME_LEN];
  fclose(ofp);
  sprintf(fname, "%s/%s.%d", 
      g.display_out_data_path, 
      DISPLAY_NAME,
      fid);
  ofp = fopen(fname, "w");
  if(ofp == NULL) {
    FATAL("fopen [%s] error", fname);
    assert(0);
  }
}
